import React, { useRef, useEffect, useState } from 'react'
import { Space, Tag, Col, Row, message, Card, Divider, Modal, Table, Drawer } from 'antd';
import { connect } from 'react-redux';
import axios from 'axios';
import {
  SmallDashOutlined
} from '@ant-design/icons';
import { withRouter } from 'react-router-dom';
function DeviceDetail(props) {
  const clipboardRef = useRef(null);
  const [messageApi, contextHolder] = message.useMessage();
  const [dataSource, setDataSource] = useState([[], [], [], [], []])
  const [gateInfo, setGateInfo] = useState([[], [], [], [], []])
  const [open, setOpen] = useState(false);
  const [data, setData] = useState([]);
  const [nowIndex, setNowIndex] = useState(0);
  const [password, setPassword] = useState(props.row.mqttpassword);
  const [nowPage, setNowPage] = useState(1);

  const copyCommand = (type) => {
    var pas
    if (type === "id") {
      pas = props.row.gatewayid
    } else if (type === "pas") {
      pas = password
    }
    if (navigator.clipboard && window.isSecureContext) {
      // navigator clipboard 向剪贴板写文本
      return navigator.clipboard.writeText(pas).then(() => {
        messageApi.open({
          type: 'success',
          content: '复制成功',
        });
      });
    } else {
      // 创建text area
      let textArea = document.createElement("textarea");
      textArea.value = pas;
      // 使text area不在viewport，同时设置不可见
      textArea.style.position = "absolute";
      textArea.style.opacity = 0;
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      return new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? res() : rej();
        textArea.remove();
        messageApi.open({
          type: 'success',
          content: '复制成功',
        });
      });
    }
    // navigator.clipboard.writeText(password).then(() => {
    //   messageApi.open({
    //     type: 'success',
    //     content: '复制成功',
    //     duration: 3,
    //   });
    // })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '设备名称',
      dataIndex: 'pointtag',
      key: 'pointtag',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '数据值',
      dataIndex: 'pointvalue',
      key: 'pointvalue',
      align: "center",
      render: (text, item) => {
        if (item.isbool === 0) {
          return <span style={{ fontSize: "12px" }}>{text}</span>
        }
        return <span style={{ fontSize: "12px" }}>{text === 0 ? "true" : "false"}</span>


      }
    },
    {
      title: '数据单位',
      dataIndex: 'pointunit',
      key: 'pointunit',
      align: "center",
      render: (text) => {
        if (text != null) {
          return <span style={{ fontSize: "12px" }}>{text}</span>
        }
        return "无"
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      key: 'updatetime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
      // },
      // {
      //   title: '操作',
      //   dataIndex: 'operate',
      //   key: 'operate',
      //   fixed: 'right',
      //   align: "center",
      //   render: (text, item) => {
      //     return <Space>
      //       <a style={{ fontSize: "12px", color: "#4e9dfd" }} >删除</a>
      //     </Space>
      //   }
    }
  ];
  // const data = [{
  //   index: "1",
  //   pointtag: "厂房A温度",
  //   pointvalue: "30.0",
  //   pointunit: "℃",
  //   updatetime: "22222",
  //   isbool: 0
  // }]
  const stateList = ["在线", "离线", "中断"]
  const colorList = ["green", "red", "orgen"]
  useEffect(() => {
    updateCard()
    const intervalID = setInterval(function () {
      updateCard()
    }, 5000);
    return () => {
      // 清除setInterval
      clearInterval(intervalID);
    };
  }, [])

  const updateCard = () => {
    axios.get("/datapoint/selectdata?id=" + props.row.id).then(res => {
      setDataSource(res.data)
    })


    axios.get("/gateway/detail?gatewayId=" + props.row.gatewayid).then(res => {
      setGateInfo(res.data)
      setPassword(res.data.mqttpassword)

    })

  }
  const paginationChange = (page) => {
    setNowPage(page)
  }
  const showData = (index) => {
    var data = []
    dataSource[1][index].map((obj, i) => {
      data[i] = {
        index: i,
        pointtag: dataSource[0][index],
        pointvalue: obj,
        pointunit: dataSource[2][index] === null ? "无" : dataSource[2][index],
        updatetime: dataSource[3][index][i],
        isbool: dataSource[4][index][i]
      }
    })
    setNowIndex(index)
    setData(data)
    setOpen(true);
  }

  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    return (
      <>
        <Table
          columns={columns} dataSource={data} style={{ margin: "5px 0 0 0" }}
          rowKey={(item) => item.index}
          pagination={{ defaultCurrent: nowPage, onChange: (page, pageSize) => paginationChange(page) }}
          size='small'
        >
        </Table>
      </>

    );
  };
  const resetPassword = () => {
    axios.get("/gateway/reset?id=" + props.row.id).then(res => {
      setPassword(res.data.mqttpassword)
    })
  }
  return (
    <div style={{ background: "white", textAlign: "left" }}>
      {contextHolder}
      <Space direction="vertical" size="middle" style={{ padding: "10px 30px 20px 30px", width: "100%" }}>
        <div style={{ fontSize: "24px", margin: "0 0 20px 0" }}>
          {gateInfo.gatewayname} <Tag color={gateInfo.gatewaystate === 0 ? "green" : "red"}
            style={{ margin: "0 0 0 20px", width: "80px", height: "24px", textAlign: 'center', borderRadius: "0px", border: "soild 0px black", color: gateInfo.gatewaystate === 0 ? "green" : "red" }}>
            {gateInfo.gatewaystate === 0 ? "在线" : "离线"}</Tag>
        </div>
        <Row>
          <Col span={22} push={2}>{gateInfo.gatewayid}
            <span ref={clipboardRef} style={{ margin: "0 0 0 20px", color: "#4e9dfd", cursor: "pointer" }} onClick={() => copyCommand("id")}>复制</span>
          </Col>
          <Col span={2} pull={22}>设备ID</Col>
        </Row>
        {/* <Row>
          <Col span={22} push={2}>{props.row.lowdevicenum}</Col>
          <Col span={2} pull={22}>下级设备数</Col>
        </Row> */}
        {/* <Row>
          <Col span={22} push={2}>{props.row.mqttuser} <span ref={clipboardRef} style={{ margin: "0 0 0 20px", color: "#4e9dfd", cursor: "pointer" }} onClick={() => copyCommand("user")}>复制</span></Col>
          <Col span={2} pull={22}>MQTT用户名</Col>
        </Row> */}
        <Row>
          <Col span={22} push={2}>{password}
            <span style={{ margin: "0 0 0 20px", color: "#4e9dfd", cursor: "pointer" }} onClick={() => resetPassword()}>重置</span>
            <span ref={clipboardRef} style={{ margin: "0 0 0 20px", color: "#4e9dfd", cursor: "pointer" }} onClick={() => copyCommand("pas")}>复制</span>
          </Col>
          <Col span={2} pull={22}>MQTT密码</Col>
        </Row>
        <Row>
          <Col span={22} push={2}>{gateInfo.createtime}</Col>
          <Col span={2} pull={22}>创建时间</Col>
        </Row>
        <Row>
          <Col span={22} push={2}>{gateInfo.introduce}</Col>
          <Col span={2} pull={22}>设备介绍</Col>
        </Row>
      </Space>
      <Divider orientation="left" style={{ fontSize: "18px", margin: "15px 0" }}>设备数据</Divider>
      {/* <Table
        rowKey={(item) => item.id}
        columns={columns} dataSource={dataSource}
        pagination={{ pageSize: 10 }}
        size='small'
      /> */}
      <Row gutter={16}>
        {
          dataSource[0].map((obj, index) => {
            return (
              <Col className="gutter-row" span={6} key={index} onClick={() => showData(index)}>
                <Card style={{ height: "140px", border: "1px solid #d9d9d9", borderRadius: '0px' }} hoverable={true} >
                  <div style={{ height: "70px", display: 'flex' }}>
                    <div style={{ flex: "1 1 150px" }}>
                      <div >{obj}</div>
                      <div style={{ fontSize: '12px' }}>{dataSource[3][index][0]}</div>
                    </div>
                    <div style={{ flex: "1 1 150px", textAlign: "right" }}><SmallDashOutlined /></div>
                  </div>
                  <div style={{ height: "70px", fontSize: '22px', fontWeight: 'bold' }}>{
                    dataSource[4][index] === 1 ? dataSource[1][index][0] === 0 ? "false" : "true" : dataSource[1][index][0] + dataSource[2][index]
                  }</div>
                </Card>
              </Col>
            )
          })
        }
      </Row>
      <Modal
        open={open}
        title={dataSource[0][nowIndex]}
        width={"1000px"}
        height={"500px"}
        footer={null}
        onCancel={() => {
          setOpen(false);
        }}
      >
        <Divider orientation="left" style={{ fontSize: "18px", margin: "15px 0" }}></Divider>
        <CollectionCreateForm
        />
      </Modal>

    </div>
  )
}
const mapStateToProps = ({ DetailOpen: { row } }) => ({
  row
})
const mapDispatchToProps = {
  setDetail(item) {
    return {
      type: "change_detailOpen",
      row: item
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(DeviceDetail));